package com.cjl.dental_clinic.controller;

import cn.hutool.core.util.RandomUtil;
import com.cjl.dental_clinic.Req.PatientMedReq;
import com.cjl.dental_clinic.Req.PatientReq;
import com.cjl.dental_clinic.base.BaseController;
import com.cjl.dental_clinic.base.ResVo;
import com.cjl.dental_clinic.entity.Order;
import com.cjl.dental_clinic.entity.Patient;
import com.cjl.dental_clinic.entity.Prescription;
import com.cjl.dental_clinic.service.OrderService;
import com.cjl.dental_clinic.service.PatientService;
import com.cjl.dental_clinic.service.PrescriptionService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: cjl
 * @time: 2024/04/09 14:29
 */
@RestController
@RequestMapping("cjl/patient")
public class PatientController extends BaseController<Patient, PatientService> {

    private final PrescriptionService prescriptionService;
    private final OrderService orderService;
    public PatientController(PatientService baseService, PrescriptionService prescriptionService, OrderService orderService) {
        super(baseService);
        this.prescriptionService = prescriptionService;
        this.orderService = orderService;
    }

    @PostMapping("list")
    public ResVo<List<PatientReq>> list(String name){
        return ResVo.ok(baseService.listPatient(name));
    }

    @PostMapping("up")
    public ResVo<Boolean> up(Integer id,Integer status){
        if (status == 2) {
            Patient patient = baseService.getById(id);
            Prescription prescription = new Prescription();
            prescription.setPatientId(id)
                    .setDoctorId(patient.getDoctorId())
            .initCreateUser();
            prescriptionService.save(prescription);
        }
        return ResVo.ok(baseService.updateStatus(id,status));
    }

    @PostMapping("updata")
    public ResVo<Boolean> upData(Patient patient){
        return ResVo.ok(baseService.updateById(patient));
    }

    @PostMapping("med")
    public ResVo<Boolean> med(PatientMedReq patientMedReq){
        return ResVo.ok(baseService.med(patientMedReq));
    }
    @PostMapping("complete")
    @Transactional(rollbackFor = Exception.class)
    public ResVo<Boolean> complete(Integer id){
        // 修改状态
        baseService.updateStatus(id,4);
        // 查询患者信息
        Patient patient = baseService.getById(id);
        // 生成订单
        Order order = new Order();
        order.setPatientId(patient.getId())
                .setDoctorId(patient.getDoctorId())
                .setInvoiceDate(new Date())
                .setId(RandomUtil.randomInt(99999));
        order.initCreateUser();
        return ResVo.ok(orderService.save(order));
    }

}
